<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="供应商" prop="partnerId">
            <PartnerSearch :dataText="pd.queryParams.partnerName" :params="{isSupplier:true}" title="请选择查询供应商"
                           @ok="searchSupplier2($event)" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="单据状态" prop="status">
            <dictSelect :dictType="'wms_order_status'" v-model:dict-value="pd.queryParams.status" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="pd.queryParams.remark" placeholder="请输入备注" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="更新时间" style="width: 290px">
            <el-date-picker
              v-model="dateRangeUpdateTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
          </el-form-item>
        </el-form>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:order:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button :disabled="!pd.single" type="primary" plain icon="Switch" @click="handleTurnOrder" v-hasPermi="['wms:order:edit']">转采购订单</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:order:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="pd.loading" :data="pd.orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="单据类别" align="center" prop="typeName" />
        <el-table-column label="名称" align="center" prop="name">
          <template #default="scope">
            <el-link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['wms:order:edit']">
              {{ scope.row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="供应商名称" align="center" prop="partnerName" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dictTag :options="wms_order_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center" prop="totalMoney" />
        <el-table-column label="优惠金额" align="center" prop="discountMoney" />
        <el-table-column label="实际金额" align="center" prop="costMoney" />
        <el-table-column label="来源单号" align="center" prop="sourceId" />
        <el-table-column label="退回单号" align="center" prop="backId" />
        <el-table-column label="申请人" align="center" prop="applicantId" />
        <el-table-column label="操作人" align="center" prop="execId" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope">

            <el-button link type="primary" icon="Finished" @click="handleTurnOrder(scope.row)"
                       v-if="scope.row.status === '1'" v-hasPermi="['wms:order:turn']"> 转采购订单
            </el-button>
            <el-button link type="primary" icon="Checked"
                       v-if="scope.row.status === '0'" > 已转采购订单
            </el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-if="scope.row.status === '1'" v-hasPermi="['wms:order:edit']"> 修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)"
                       v-if="scope.row.status === '1'" v-hasPermi="['wms:order:remove']">删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <Pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改测试主从对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="1000" append-to-body>
      <el-form ref="orderFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商" prop="partnerId">
              <PartnerSearch :dataText="pd.form.partnerName" :params="{isSupplier:true}" @ok="searchSupplier1($event)" />
            </el-form-item>
            <el-form-item label="选择仓库" prop="selfWhId">
              <WarehouseSelect :params="{parentId:0}" v-model:whId="pd.form.selfWhId" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入单据名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <DictSelect disabled :dictType="'wms_order_status'" v-model:dictValue="pd.form.status" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row :gutter="10" class="mb8">

        <el-col :span="1.5">
          <el-button v-if="!pd.form.id" icon="Plus" type="success" @click="submitForm">保存单据</el-button>
          <el-button v-if="pd.form.id" icon="Delete" type="danger" @click="handleDelete(pd.form.id)">删除单据</el-button>
        </el-col>
        <el-col v-if="pd.form.id" :span="1.5">
          <el-button icon="Plus" type="success" @click="submitForm">修改单据</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Close" type="info" @click="pd.dialog.visible = false">关闭</el-button>
        </el-col>
        <el-col :span="1.5">
          <ProductSearch :searchType="2" :params="{isStock:true,isPurchase:true}" @ok="lineAdd" title="产品查询" dataText="新增一行" />
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Refresh" @click="getLineList">刷新</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="pd.loading" :data="pd.form.line">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="物品名称" align="center" prop="productName" />
        <el-table-column label="单位" align="center" prop="measureUnit" />
        <el-table-column label="批次号" align="center" prop="batchCode">
          <template #default="scope">
            <el-input v-model="scope.row.batchCode" placeholder="请输入批次号" />
          </template>
        </el-table-column>
        <el-table-column label="采购价" align="center" prop="price">
          <template #default="scope">
            <el-input @input="computCostMoney(scope.row)" v-model="scope.row.price" placeholder="请输入采购价" />
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="quantity">
          <template #default="scope">
            <el-input @input="computCostMoney(scope.row)" v-model="scope.row.quantity" placeholder="请输入优惠金额" />
          </template>
        </el-table-column>

        <el-table-column label="总金额" align="center" prop="totalMoney" />
        <el-table-column label="优惠金额" align="center" prop="quantity">
          <template #default="scope">
            <el-input @input="computCostMoney(scope.row)" v-model="scope.row.discountMoney" placeholder="请输入优惠金额" />
          </template>
        </el-table-column>
        <el-table-column label="应收金额" align="center" prop="costMoney">
          <template #default="scope">
            <el-input @input="computDiscountMoney(scope.row)" v-model="scope.row.costMoney" placeholder="应收金额" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="delLine(scope.row)" v-hasPermi="['wms:order:del']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="pd.lineTotal>0" :total="pd.lineTotal" v-model:page="pd.queryLineParams.pageNum"
                  v-model:limit="pd.queryLineParams.pageSize" @pagination="getLineList" />
    </el-dialog>
    <!-- 查看 -->
    <el-dialog :title="pd.inspectionDialog.title" v-model="pd.inspectionDialog.visible" width="1000">
      <el-descriptions>
        <el-descriptions-item label="供应商">{{ pd.form.partnerName }}</el-descriptions-item>
        <el-descriptions-item label="单据名称">{{ pd.form.name }}</el-descriptions-item>
        <el-descriptions-item label="单据编号">{{ pd.form.id }}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{ pd.form.warehouseName }}</el-descriptions-item>
      </el-descriptions>
      <el-table :data="pd.form.line" stripe style="width: 100%">
        <el-table-column prop="productName" label="物品名称" width="120" />
        <el-table-column prop="measureUnit" label="单位" width="120" />
        <el-table-column prop="batchCode" label="批次号" width="120" />
        <el-table-column prop="price" label="采购价" width="120" />
        <el-table-column prop="quantity" label="数量" width="120" />
        <el-table-column prop="totalMoney" label="总金额" width="120" />
        <el-table-column prop="discountMoney" label="优惠金额" width="120" />
        <el-table-column prop="costMoney" label="实际金额" />
      </el-table>
      <pagination class="print-hidden" v-show="pd.lineTotal>0" :total="pd.lineTotal" v-model:page="pd.queryLineParams.pageNum"
                  v-model:limit="pd.queryLineParams.pageSize" @pagination="getLineList" />
      <el-col :span="1.5">
        <el-button class="print-hidden" style="float: inherit" type="primary" @click="print">打印</el-button>
      </el-col>
    </el-dialog>
  </div>
</template>

<!-- 采购订单-->
<script setup name="OrderPurchase" lang="ts">
import {
  OrderLineVO, OrderVO, addOrder, backOrder, delOrder, delOrderLine, execOrder, listOrder, listOrderLine,
  updateOrder, FinancialSettlement, turnOrder
} from '@/views/wms/order/api';
import {ProductVO} from "@/views/wms/product/api";
import ProductSearch from '@/views/wms/product/search.vue';
import PartnerSearch from '@/views/hrp/partner/search.vue';
import DictSelect from '@/views/system/dict/select.vue';
import {PartnerVO} from "@/views/hrp/partner/api";

import WarehouseSelect from "@/views/wms/warehouse/select.vue";
const route = useRoute();

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {wms_order_status} = toRefs<any>(proxy?.useDict('wms_order_status'));
const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();

const pd = reactive({
  orderList: <OrderVO[]>([]),
  selected: <OrderVO[]>([]),
  single: false,
  buttonLoading: false,
  loading: true,
  showSearch: true,
  total: 0,
  lineTotal: 0,
  form: <OrderVO>{},
  dialog: <DialogOption>{
    visible: false,
    title: ''
  },
  inspectionDialog: <DialogOption>{
    visible: false,
    title: '采购订单-详情'
  },
  queryParams: <OrderVO>{
    pageNum: 1,
    pageSize: 10
  },
  queryLineParams: <OrderLineVO>{
    pageNum: 1,
    pageSize: 10,
    id: undefined
  },
  rules: <ElFormRules>{
    typeId: [{required: true, message: "单据类别不能为空", trigger: "change"}],
    name: [{required: true, message: "单据名称不能为空", trigger: "blur"}],
    partnerId: [{required: true, message: "供应商不能为空", trigger: "blur"}],
    selfWhId: [{required: true, message: "仓库不能为空", trigger: "blur"}],
    status: [{required: true, message: "状态不能为空", trigger: "change"}]
  }
});

/** 转采购订单  */
async function handleTurnOrder(vo: OrderVO) {
  let boList = [];
  if (pd.single){
    const orderNames = pd.selected.map(order => order.name).join(", ");
    await proxy?.$modal.confirm("确认将单据："+orderNames+" 转为采购订单吗?");
    boList = pd.selected;
  }else{
    await proxy?.$modal.confirm("确认将单据："+vo.name+" 转为采购订单吗?");
    boList.push(vo)
  }
  for (let i = 0; i < boList.length; i++) {
    if(boList[i].status === "0"){
      proxy?.$modal.msgWarning("所选单据包含已转换采购订单，请重新选择!");
      return;
    }
    if (boList[i].selfWhId != boList[0].selfWhId){
      proxy?.$modal.msgWarning("所选单据仓库号不一致，请重新选择!");
      return;
    }
    if (!boList[i].partnerId){
      proxy?.$modal.msgWarning("单据 "+boList[i].id+" 未选择供应商!");
      return;
    }
    if (boList[i].partnerId != boList[0].partnerId){
      proxy?.$modal.msgWarning("所选单据供应商不一致！")
      return;
    }
  }
  await turnOrder(boList).then(res => {
    proxy?.$modal.msgSuccess("订单已转为采购订单");
  }).finally(()=>{getList()});
}

/** 冲销  */
async function handleBackOrder(vo: OrderVO) {
  await proxy?.$modal.confirm("确认要冲销单据："+vo.name+" 吗?");
  await backOrder(<OrderVO>vo).then(res => {
    proxy?.$modal.msgSuccess("冲销单已生成，请前往采购退货页面处理");
    getList()
  });
}

/** 财务结算  */
async function handleFinance(vo: OrderVO) {
  await proxy?.$modal.confirm("确认要结算单据："+vo.name+" 吗?");
  await FinancialSettlement(vo).then(res => {
    proxy?.$modal.msgSuccess("财务结算单已生成");
    getList();
  });
}

/** 订单确认状态修改  */
async function handleSendOrder(row: OrderVO){
  if (! ( row.status === "1" )){
    return;
  }
  try {
    await proxy?.$modal.confirm('确认要发送"' + row.name + '" 订单吗?');
    row.status="3";
    await updateOrder(row);
    proxy?.$modal.msgSuccess(row.name + "成功");
  } catch (err) {
    // row.status = row.status === "1" ? "3" : "0";
  }
}

function searchSupplier1(pVo: PartnerVO[]) {
  pd.form.partnerId = pVo[0].id;
  pd.form.partnerName = pVo[0].name;
}

function searchSupplier2(pVo: PartnerVO[]) {
  pVo.forEach((v, i, a) => {
    pd.queryParams.partnerId = v.id;
    pd.queryParams.partnerName = v.name;
    return;
  });
}

/** 查询测试主从列表 */
async function getList() {
  pd.loading = true;
  pd.queryParams.params = {};
  proxy?.addDateRange(pd.queryParams, dateRangeUpdateTime.value, 'UpdateTime');
  const res = await listOrder(pd.queryParams);
  pd.orderList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 查询测试子列表 */
async function getLineList() {
  pd.loading = true;
  pd.queryLineParams.id = pd.form.id;
  await listOrderLine(pd.queryLineParams).then(res => {
    pd.form.line = res.rows;
    pd.lineTotal = res.total;
    pd.loading = false;
  });
}

/** 表单重置 */
const reset = () => {
  pd.form = {pageNum: 0, pageSize: 0};
  pd.form.line = [];
  pd.form.typeId = pd.queryParams.typeId;
  orderFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeUpdateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  pd.queryParams.partnerName = '';
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: OrderVO[]) {
  pd.selected = selection;
  pd.single = selection.length > 0;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.form.status = '1';
  pd.dialog.title = "新增采购订单"
  pd.dialog.visible = true;
}

/** 新增一行按钮操作 */
async function lineAdd(vo: ProductVO[]) {
  let line: OrderLineVO = {};
  vo.forEach((v, i, a) => {
    line.productId = v.id as number;
    line.productName = v.name;
    line.price = v.purchasePrice;
    line.measureUnit = v.measureUnit;
    line.quantity = 1;
    line.totalMoney = v.purchasePrice;
    line.discountMoney = 0;
    line.costMoney = line.totalMoney! - line.discountMoney;
    pd.form.line!.push(line);
  });
}

// 计算金额
function computCostMoney(vo: OrderLineVO) {
  vo.totalMoney = vo.quantity! * vo.price!;
  vo.costMoney = vo.totalMoney - vo.discountMoney!;
}

// 计算金额
function computDiscountMoney(vo: OrderLineVO) {
  vo.totalMoney = vo.quantity! * vo.price!;
  vo.discountMoney = vo.totalMoney - vo.costMoney!;
}
/** 修改按钮操作 */
async function handleUpdate(row?: OrderVO) {
  reset();
  Object.assign(pd.form, row);
  await getLineList();
  if (row?.status == "0" || row?.status == "8"){
    pd.inspectionDialog.visible = true;
    pd.inspectionDialog.title = '采购退货-详情';
    return
  }
  pd.dialog.visible = true;
  pd.dialog.title = "修改采购订单";
}

/** 提交按钮 */
function submitForm() {
  orderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (pd.form.id) {
        pd.buttonLoading = true;
        await updateOrder(pd.form).then((res: any) => {
          pd.buttonLoading = false
          proxy?.$modal.msgSuccess(res.msg);
        });
      } else {
        await addOrder(pd.form).then((res: any) => {
          pd.buttonLoading = false
          proxy?.$modal.msgSuccess(res.msg);
        });
      }
      pd.dialog.visible = false;
      await getList();
    }
  })
}

/** 删除按钮操作 */
async function handleDelete(id: number) {
  await proxy?.$modal.confirm('是否确认删除测试主从编号为"' + id + '"的数据及子数据？').finally(() => pd.loading = false);
  await delOrder(id as number);
  proxy?.$modal.msgSuccess("删除成功");
  pd.dialog.visible = false;
  await getList();
}

/** 删除子表操作 */
async function delLine(row: OrderLineVO) {
  if (row.lineId === undefined) {
    const index = pd.form.line!.indexOf(row);
    pd.form.line!.splice(index, 1);
    return;
  }

  proxy?.$modal.confirm('是否确认删除 子单号为:"' + row.lineId + '"的数据项？').then(function () {
    return delOrderLine(row.lineId as number);
  }).then(() => {
    const index = pd.form.line!.indexOf(row);
    pd.form.line!.splice(index, 1);
    proxy.$modal.msgSuccess("删除成功");
    // getLineList();
  }).catch(() => {
  });

}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('demo/order/export', {
    ...pd.queryParams
  }, `order_${new Date().getTime()}.xlsx`)
}

function print(){
  window.print();
}

onMounted(() => {
  pd.queryParams.typeId = parseInt(route.query.typeId as string);
  pd.form.typeId = parseInt(route.query.typeId as string);
  if (route.query.status)
    pd.queryParams.status = route.query.status as string;
  if (route.query.beginUpdateTime && route.query.endUpdateTime) {
    dateRangeUpdateTime.value = [route.query.beginUpdateTime as string + " 00:00:00",route.query.endUpdateTime as string + " 00:00:00"];
  }
  getList();
});
</script>

<style lang="scss">
@media print {
  .print-hidden {
    display: none !important;
  }
}
</style>
